using HCore.Unity.Core;
using HCore.Unity.Extension;
using UnityEngine;

namespace HCore.Tests.Runtime.PathFinding
{
    public class TestAStartSearch : MonoBehaviour
    {
        [SerializeField] private PathFindingVisual PathFindingVisual;
        private AStartSearch mAStartSearch;

        private void Awake()
        {
            mAStartSearch = CreatePathFinding(10, 10, 10f, Vector2.one * -50);
        }

        private void Start()
        {
            PathFindingVisual.SetGrid(mAStartSearch.Grid);
        }

        private void Update()
        {
            // 鼠标左键，开始寻路
            if (Input.GetMouseButtonDown(0))
            {
                var mouseWorldPosition = GameUtils.GetWorldPositionFromScreen().ToVector2();
                var grid = mAStartSearch.Grid;
                grid.GetCellXY(mouseWorldPosition, out var x, out var y);

                // 这里测试一条路径
                var pathNodes = mAStartSearch.FindPaths(0, 0, x, y);
                if (pathNodes != null)
                    for (var i = 0; i < pathNodes.Count - 1; i++)
                        Debug.DrawLine(grid.GetCellWorldPosition(pathNodes[i].X, pathNodes[i].Y) + Vector2.one * 5f,
                            grid.GetCellWorldPosition(pathNodes[i + 1].X, pathNodes[i + 1].Y) + Vector2.one * 5f,
                            Color.green,
                            10f
                        );
            }

            // 鼠标右键，设置障碍
            if (Input.GetMouseButtonDown(1))
            {
                var mouseWorldPosition = GameUtils.GetWorldPositionFromScreen().ToVector2();
                mAStartSearch.Grid.GetCellXY(mouseWorldPosition, out var x, out var y);
                mAStartSearch.GetNode(x, y).IsWalkable = !mAStartSearch.GetNode(x, y).IsWalkable;
                mAStartSearch.Grid.TriggerCellChanged(x, y);
            }
        }

        /// <summary>
        ///     创建一个A*路径查找实例
        /// </summary>
        /// <param name="width">网格的宽度（单元格数量）</param>
        /// <param name="height">网格的高度（单元格数量）</param>
        /// <param name="cellSize">每个网格单元格的大小，默认为10f</param>
        /// <param name="originPosition">网格的起始位置，默认为Vector2.zero</param>
        /// <returns>返回一个新的AStartSearch路径查找实例</returns>
        public static AStartSearch CreatePathFinding(int width, int height, float cellSize = 10f,
            Vector2 originPosition = default)
        {
            // 创建一个新的A*搜索实例，使用Grid2D网格和PathNode节点
            return new AStartSearch(new Grid2D<IPathNode>(
                width, height,
                (_, x, y) => new PathNode(x, y),
                originPosition, cellSize)
            );
        }
    }
}